<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-button size="small" type="success" @click="openAdditionDialog()">+
          {{$t('message.term.add')}}
        </el-button>

      </div>
      <el-form style="padding: 0 10px" :inline="true" :model="formInline" class="demo-form-inline" size="small">
        <el-row :gutter="20">
          <el-col :span="20">
            <el-form-item :label="$t('message.term.name')">
              <el-input v-model="formInline.name" clearable></el-input>
            </el-form-item>
            <el-form-item :label="$t('message.term.configuration')">
              <el-input v-model="formInline.configuration" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item class="fr">
              <el-button type="primary" @click="query(1)">{{$t('message.term.search')}}</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <PaginationTable :loading="loadingForPaginationTable" :columns="columnsDef" :data="tablePaginationData"
                       @onCurrentChange="handleCurrentPageChange"
                       @onPageSizeChange="onPageSizeChange"
                       :headerCellStyle="{background:'#f5f7fa'}">
      </PaginationTable>
    </el-card>

    <!-- 对话框 -->
    <el-dialog :title="auDialog.title" :visible.sync="auDialog.visible" :close-on-click-modal="false"
               @close="onAUDialogClose">
      <div style="padding-right: 10px;">
        <el-form :model="formAU" ref="formAU" size="small">
          <el-form-item :label="$t('message.term.name')"
                        :label-width="auDialog.formLabelWidth" prop="name">
            <el-input v-model="formAU.name" autocomplete="off"></el-input>
          </el-form-item>

          <el-form-item :label="$t('message.term.sequence')"
                        :label-width="auDialog.formLabelWidth" prop="sequence">
<!--            <el-input v-model="formAU.sequence" autocomplete="off"></el-input>-->
            <el-input-number v-model="formAU.sequence" @change="handleChange"></el-input-number>
          </el-form-item>

          <el-form-item :label="$t('message.term.configuration')"
                        :label-width="auDialog.formLabelWidth" prop="configuration">
            <el-input type="textarea" v-model="formAU.configuration" autocomplete="off"></el-input>
          </el-form-item>

          <el-form-item :label="$t('message.term.comment')"
                        :label-width="auDialog.formLabelWidth" prop="comment">
            <el-input v-model="formAU.comment" autocomplete="off"></el-input>
          </el-form-item>

        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeAUDialog" size="small">{{$t('message.term.cancel')}}</el-button>
        <el-button type="primary" @click="confirmSubmitAUDialog" size="small">{{$t('message.term.confirm')}}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {API} from '@/customized/http/api';
import Util from '@/customized/util/utils.js';
import PaginationTable from '@/components/PaginationTable';

export default {
  name: "widget",
  components: {
    PaginationTable
  },
  data() {
    return {
      namespace: "widget.",
      /** 查询对应的表单 */
      formInline: {
        name: '',
        configuration:'',
        page_size: 0
      },
      /** 新增及编辑对话框对应的表单 */
      formAU: {
        id: '',
        version: '',
        name: '',
        sequence: '',
        configuration: '',
        comment: ''
      },
      /** 对话框的属性 */
      auDialog: {
        visible: false,
        title: "",
        formLabelWidth: '160px'
      },
      /** 数据表是否显示正在加载中的提示 */
      loadingForPaginationTable: false,
      currentPage: 1,
      /** 数据表列的定义 */
      columnsDef: [{
        prop: "name",
        label: this.$t('message.term.name'),
      }, {
        prop: "sequence",
        label: this.$t('message.term.sequence')
      }, {
        prop: "configuration",
        label: this.$t('message.term.configuration')
      }, {
        prop: "comment",
        label: this.$t('message.term.comment')
      }, {
        label: this.$t('message.term.action'),
        prop: 'action',
        fixed: "right",
        width: 120,
        render: (h, params) => {
          return h('div', [
            h('el-button', {
              props: {
                type: 'text',
                size: 'small'
              },
              style: {
                color: '#f56c6c'
              },
              on: {
                click: () => {
                  this.handleDeleteButton(params);
                }
              }
            }, this.$t('message.term.delete')),
            h('el-button', {
              props: {
                type: 'text',
                size: 'small'
              },
              on: {
                click: () => {
                  this.handleEditButton(params);
                }
              }
            }, this.$t('message.term.edit'))
          ]);
        }
      }],
      /** 数据表绑定的数据集 */
      tablePaginationData: {},
      validatorFields: []
    }
  },
  created() {

  },
  mounted: function () {
    this.$nextTick(() => {
      this.query(this.currentPage);
    });
  },
  beforeDestroy: function () {

  },
  computed: {

  },
  methods: {
    handleChange(value) {
      console.log(value);
    },
    tableHeadRender(h, data) {
      return h('span', [
        h('el-tooltip', {attrs:{ content:data.column.label }}, [h('span', data.column.label)])
      ])
    },
    showFullScreenLoading() {
      const loading = this.$loading({
        lock: true
      });
      return loading;
    },
    onPageSizeChange(pageSize) {
      this.formInline.page_size = pageSize;
      this.query(this.currentPage);
    },
    /** 查询配置项 */
    query(page) {
      this.currentPage = page;
      let postJson = {
        page: page,
        ...this.formInline
      };

      this.loadingForPaginationTable = true;
      API.queryWidget(postJson)
          .then((responseData) => {
            this.loadingForPaginationTable = false;
            this.tablePaginationData = responseData.data;
          })
          .catch((exception) => {
            this.$message.error(exception.message);
            this.loadingForPaginationTable = false;
          });
    },
    /** 换页 */
    handleCurrentPageChange(newPage) {
      this.query(newPage);
      this.currentPage = newPage;
    },
    /** 点击删除按钮 */
    handleDeleteButton(params) {
      let id = params.row.id;
      let version = params.row.version;
      this.$confirm(this.$t('message.term.confirm_deleting'), this.$t('message.term.tips'), {
        confirmButtonText: this.$t('message.term.confirm'),
        cancelButtonText: this.$t('message.term.cancel'),
        type: 'warning'
      }).then(() => {
        this.remove(id, version);
      }).catch((exception) => {
        let exceptionJson = JSON.parse(exception.message);
        this.$message.error(exceptionJson.message);
      });
    },
    /** 点击数据行的编辑按钮 */
    handleEditButton(params) {
      /** 全局加载中开启 */
      const loading = this.$loading({
        lock: true
      });

      API.getWidgetItem({id: params.row.id}).then((res) => {
        let itemDetail = res.data;

        /** 打开编辑对话框 */
        this.auDialog.title = this.$t('message.term.edit') + this.$t('message.term.po_status');
        this.auDialog.visible = true;

        /**
         * form表单的重置是以第一次打开的数据作为重置标准,如果先打开的是更新,那么重置之后以第一次更新的数据作为标准;
         * Dialog 中的内容是懒加载的，目前 edit (更新)方法的写法导致 Form 刚加载出来时值就已经是新的了，
         * 所以 resetFields 也只能回到新值
         */
        this.$nextTick(() => {
          for (let attr in this.formAU) {
            let attrValue = itemDetail[attr];
            /** 只复制我们需要的属性 */
            this.formAU[attr] = attrValue ? attrValue : "";
          }
        });

        /** 全局加载中关闭 */
        loading.close();
      }).catch((exception) => {
        this.$message.error(exception.message);
        loading.close();
      });
    },
    /** 关闭对话框 */
    closeAUDialog() {
      this.auDialog.visible = false;
    },
    /** 能同时兼顾点按钮关闭和点右上角的X关闭 */
    onAUDialogClose() {
      this.auDialog.title = "";
      this.formAU.id = null;
      this.formAU.version = null;
      this.$refs.formAU.resetFields();
    },
    /** 确定提交新增 */
    confirmSubmitAUDialog() {
      let postJson = {
        ...this.formAU
      };
      this.$refs['formAU'].validate((valid) => {
        if (valid) {
          if (!Util.isBlank(this.formAU.id) && !Util.isBlank(this.formAU.version)) {
            this.update(postJson);
          } else {
            this.add(postJson);
          }
        } else {
          this.$message.error(this.$t('message.term.validate_fail'));
        }
      })

      console.log(JSON.stringify(postJson));
    },
    /** 新增配置项 */
    add(postJson) {
      console.log(JSON.stringify(postJson))
      API.addWidget(postJson)
          .then(() => {
            /** 提示成功 */
            this.$message({
              type: 'success',
              message: this.$t('message.term.add') + " "
                  + this.$t('message.term.po_status') + " "
                  + this.$t('message.term.success')
            });
            this.closeAUDialog();
            this.query(this.currentPage);
          })
          .catch((exception) => {
            this.$message.error(exception.message);
          });
    },
    /** 修改配置项 */
    update(postJson) {
      API.updateWidget(postJson)
          .then(() => {
            /** 提示成功 */
            this.$message({
              type: 'success',
              message: this.$t('message.term.edit') + " "
                  + this.$t('message.term.po_status') + " "
                  + this.$t('message.term.success')
            });
            this.closeAUDialog();
            this.query(this.currentPage);
          })
          .catch((exception) => {
            this.$message.error(exception.message);
          });
    },
    /** 删除配置项 */
    remove(id, version) {
      API.removeWidget({id: id, version: version})
          .then(() => {
            /** 提示成功 */
            this.$message({
              type: 'success',
              message: this.$t('message.term.delete') + " "
                  + this.$t('message.term.po_status') + " "
                  + this.$t('message.term.success')
            });

            this.query(this.currentPage);
          })
          .catch((exception) => {
            let exceptionJson = JSON.parse(exception.message);
            this.$message.error(exceptionJson.message);
          });
    },
    /** 打开新增对话框 */
    openAdditionDialog() {
      this.auDialog.title = this.$t('message.term.add') + " " + this.$t('message.term.record');
      this.auDialog.visible = true;
    },
  }
}
</script>